<?php

require_once __DIR__ . '/../../../vendor/autoload.php';

use JLPay\Core\OrgConfig;
use JLPay\Core\DemoConfig;
use JLPay\Services\MerchantService;
use JLPay\Models\Merchant\MerchantIncomingAddRequest;
use JLPay\Utils\Logger;
use JLPay\Utils\DemoRequestHandler;

/**
 * 商户进件示例
 */

// =================== 常量定义 =====================
// 产品类型常量
const PRODUCT_TYPE_QR_CODE = "01";  // 扫码商户：适用于码牌类商户，支持微信/支付宝/银联二维码交易
const PRODUCT_TYPE_STANDARD = "02";  // 标准商户：适用于POS类商户，支持银行卡+微信/支付宝/银联二维码交易
const PRODUCT_TYPE_SCENE = "03";  // 场景商户：特定准入商户标准,以人工申请结果为准
const PRODUCT_TYPE_SAAS = "04";  // SaaS商户：适用于SaaS类商户，支持微信/支付宝/银联二维码/银行卡交易

// 签约模式常量
const SIGN_MODE_PAPER = "P";  // 线下纸质协议
const SIGN_MODE_ELECTRONIC = "E";  // 电子签章协议
const SIGN_MODE_JLPAY = "J";  // 嘉联电子协议

// 联系人类型常量
const CONTACT_TYPE_LEGAL_PERSON = "65";  // 经营者/法人
const CONTACT_TYPE_OPERATOR = "66";  // 经办人（经商户授权办理支付业务的人员）

// 商户身份类型常量
const MERCH_TYPE_MICRO = "0";  // 小微
const MERCH_TYPE_ENTERPRISE = "1";  // 营业执照、政府机关、事业单位或其他组织

// 结算类型常量
const SETTLE_TYPE_LEGAL_PERSON_CARD = "01";  // 打款至法人银行卡
const SETTLE_TYPE_PUBLIC_ACCOUNT = "02";  // 打款至对公账户
const SETTLE_TYPE_PRIVATE_AUTHORIZED = "03";  // 对私授权收款，打款至他人银行卡
const SETTLE_TYPE_PUBLIC_AUTHORIZED = "04";  // 对公授权收款，打款至他人对公账户

// 结算关系常量
const SETTLE_RELATION_SHAREHOLDERS = "01";  // 股东/雇佣
const SETTLE_RELATION_BRANCHES = "02";  // 总分公司
const SETTLE_RELATION_PARENT_SUBSIDIARY = "03";  // 母子公司
const SETTLE_RELATION_OTHER = "09";  // 其它

// 全局变量,用于存储当前使用的apply_id
$currentApplyId = "";

// =================== 工具函数 =====================
/**
 * 创建配置对象
 */
function createConfig(): OrgConfig
{
    return DemoConfig::createConfigWithCrypto();
}

/**
 * 生成唯一的apply_id
 */
function generateApplyId(): string
{
    global $currentApplyId;
    $currentApplyId = "1vzougr30f9vcw" . substr(md5(uniqid()), 0, 16);
    return $currentApplyId;
}

// =================== 商户进件请求构建函数 =====================
/**
 * 构建商户基础信息
 */
function buildBaseInfo(): array
{
    $applyId = generateApplyId();
    
    return [
        "apply_id" => $applyId,
        "product_type" => PRODUCT_TYPE_SAAS,
        "sign_mode" => SIGN_MODE_ELECTRONIC,
        "delegatee_sign_mode" => SIGN_MODE_ELECTRONIC,
        "agreement_pic" => "jlpay-test/managefile/2024/02/28/1709081506952_af4f376e39d64abeb5dfb8a0c6db0da7.png",
        "agent_id" => "50720711",
        "qrcode_term_auto" => "1",
        "contact_info" => [
            "contact_type" => CONTACT_TYPE_LEGAL_PERSON,
            "contact_name" => "王一",
            "contact_phone" => "13800138000",
            "contact_id_no" => "110101199003077758"
        ]
    ];
}

/**
 * 构建商户身份信息
 */
function buildIdentificationInfo(): array
{
    return [
        "merch_type" => MERCH_TYPE_ENTERPRISE,
        "license_info" => [
            "license_type" => "02",  // 企业
            "license_name" => "营业执照上的名称",
            "license_no" => "91330108MABTT5NP6U",
            "period_begin" => "2024-01-01",
            "period_end" => "2030-01-01",
            "license_pic" => "jlpay-test/managefile/2024/02/28/1709081506952_af4f376e39d64abeb5dfb8a0c6db0da7.png",
            "business_scope" => "经营范围"
        ],
        "identity_info" => [
            "id_doc_type" => "01",  // 身份证
            "id_card_name" => "王一",
            "id_card_no" => "110101199003077758",
            "legal_person_phone" => "13800138000",
            "card_period_begin" => "2024-01-01",
            "card_period_end" => "2030-01-01",
            "id_card_address" => "住址",
            "id_card_copy" => "jlpay-test/managefile/2024/02/28/1709081474283_7ddfb60f42d94f8094ec88d7c78ec4a3.png",
            "id_card_national" => "jlpay-test/managefile/2024/02/28/1709081506952_af4f376e39d64abeb5dfb8a0c6db0da7.png",
        ]
    ];
}

/**
 * 构建商户经营信息
 */
function buildBusinessInfo(): array
{
    return [
        "merch_shortname" => "商户经营名称",
        "mcc_code" => "5311",
        "address_code" => "440305",
        "address_detail" => "深圳市南山区工业一路22501号",
        "door_pic" => "jlpay-test/managefile/2024/02/28/1709081506952_af4f37.png",
        "indoor_pic" => "jlpay-test/managefile/2024/02/28/1709081506952_af4f37.png",
        "cashier_pic" => "jlpay-test/managefile/2024/02/28/1709081506952_af4f37.png",
    ];
}

/**
 * 构建商户结算账户信息
 */
function buildSettlementInfo(): array
{
    return [
        "settle_type" => SETTLE_TYPE_LEGAL_PERSON_CARD,
        "settle_relation" => SETTLE_RELATION_BRANCHES,
        "account_info" => [
            "account_no" => "6227001215950896532",
            "account_name" => "王一",
            "cert_type" => "01",  // 身份证
            "bank_code" => "082",
            "bank_branch_id" => "105584000370",
            "bank_branch_name" => "中国建设银行股份有限公司深圳罗湖支行",
            "account_pic" => "jlpay-test/managefile/2024/02/28/1709106666879_6c53af86b9654680a727b92795dce6c2.jpg",
        ],
        "other_info" => [
            "identity_face_pic" => "jlpay-test/managefile/2024/02/28/1709106666879_6c53af86b9654680a727b92795dce6c2.jpg"
        ]
    ];
}

/**
 * 构建费率信息条目
 */
function buildRateInfo(string $feeCalcType, string $rate, string $minAmt = "0", string $maxAmt = "-1", 
                      string $fixed = "0", string $bottom = "0", string $top = "-1", 
                      string $step = "0", string $baseAmount = "0", string $baseFee = "0"): array
{
    return [
        "fee_calc_type" => $feeCalcType,
        "rate" => $rate,
        "min_amt" => $minAmt,
        "max_amt" => $maxAmt,
        "fixed" => $fixed,
        "bottom" => $bottom,
        "top" => $top,
        "step" => $step,
        "base_amount" => $baseAmount,
        "base_fee" => $baseFee
    ];
}

/**
 * 构建商户结算规则和费率规则
 */
function buildSettlementRule(): array
{
    // 根据服务器错误信息，rate_info应该是数组，不是单个对象
    $rateInfo = [
        buildRateInfo("30", "0.38"),  // 微信
        buildRateInfo("31", "0.38"),  // 支付宝
        buildRateInfo("03", "0.38"),  // 银联二维码（交易金额 <= 1000元）
        buildRateInfo("66", "0.45", "0", "-1", "0", "0", "1900"),  // 1000元以上银联二维码借记卡 (封顶19元)
        buildRateInfo("67", "0.55"),  // 1000元以上银联二维码贷记卡 (不封顶)
        buildRateInfo("01", "0.45", "0", "-1", "0", "0", "1900"),  // 银联内卡借记卡 (封顶19元)
        buildRateInfo("02", "0.55"),  // 银联内卡贷记卡 (不封顶)
    ];
    
    return [
        "settle_info" => [
            "settle_mode" => "7",
            "day_cut" => "000000",
            "settle_session" => "040000",
            "account_change_flag" => "0",
        ],
        "rate_info" => $rateInfo
    ];
}

/**
 * 构建其他附加信息
 */
function buildAdditionalInfo(): array
{
    return [
        "report_info" => [],
        "spec_info" => [
            "settle_type" => "01",
            "account_no" => "6227001215950896532",
            "account_name" => "王一",
            "bank_code" => "308",
            "bank_branch_id" => "105584000370",
            "bank_branch_name" => "中国建设银行股份有限公司深圳罗湖支行",
            "account_pic" => "jlpay-test/managefile/2024/02/28/170910666"
        ]
    ];
}

/**
 * 构建短信配置
 */
function buildSmsConfig(): array
{
    return [];
}

/**
 * 构建商户业务功能配置
 */
function buildFuncInfo(): array
{
    return [];
}

/**
 * 构建品牌连锁商户进件配置信息
 */
function buildChainStoreInfo(): array
{
    return [
        // 可按需添加以下字段
        // "level" => "1",
        // "main_merch_no" => "12345678",
        // "at_mode" => "0"
    ];
}

/**
 * 构建品牌信息
 */
function buildBrandInfo(): array
{
    return [
        // 可按需添加以下字段
         "brand_name" => "XX品牌",
         "brand_mark_pic" => "jlpay-test/managefile/2024/02/28/1709081506952_af4f37.png",
         "brand_auth_pic" => "jlpay-test/managefile/2024/02/28/1709081506952_af4f37.png",
         "contact_name" => "王一",
         "contact_phone" => "13800138000"
    ];
}

// =================== 商户进件示例 =====================
/**
 * 商户进件示例
 */
function merchantIncomingAddDemo(): void
{
    $logger = Logger::getInstance();
    $logger->info("开始执行商户进件示例");
    
    // 创建配置对象和商户服务
    $config = createConfig();
    $merchantService = new MerchantService($config);
    
    // 创建商户进件请求
    $request = new MerchantIncomingAddRequest();
    
    // 设置各项信息
    $request->setBaseInfo(buildBaseInfo())
        ->setIdentificationInfo(buildIdentificationInfo())
        ->setBusinessInfo(buildBusinessInfo())
        ->setSettlementInfo(buildSettlementInfo())
        ->setSettlementRule(buildSettlementRule())
        ->setAdditionalInfo(buildAdditionalInfo())
        ->setSmsConfig(buildSmsConfig())
        ->setFuncInfo(buildFuncInfo())
        // ->setChainStoreInfo(buildChainStoreInfo())
         ->setBrandInfo(buildBrandInfo());
    
    // 发送请求 - 使用DemoRequestHandler
    $response = DemoRequestHandler::sendRequestAndHandleResponse(
        $merchantService, 
        $request, 
        "商户进件",
        function($service, $request) {
            return $service->merchantIncomingAdd($request);
        }
    );
    
    // 处理响应结果
    if ($response && $response->isSuccess() && method_exists($response, 'getApplyId') && $response->getApplyId()) {
        $logger->info("申请单编号: " . $response->getApplyId());
    }
    
    $logger->info("商户进件示例执行完毕");
}

// =================== 主程序 =====================
if (php_sapi_name() === 'cli') {
    $logger = Logger::getInstance();
    
    // 设置日志级别为INFO
    $logger->setLevel('INFO');
    
    $logger->info(str_repeat("=", 50));
    $logger->info("===== 商户进件示例 开始 =====");
    $logger->info(str_repeat("=", 50));
    merchantIncomingAddDemo();
    
    $logger->info("\n" . str_repeat("=", 50));
    $logger->info("===== 商户进件示例执行完毕 =====");
    $logger->info(str_repeat("=", 50));
} 